Ext.define('BookmarkIt.store.gapiManager',{
	singleton:true,
	constructor:function(config){
		this.updateStack=[];
	},
	tryCount:0,
	loadDataToStore: function(store){
		var me = this;		
		gapi.client.load('drive', 'v2', function() {
			gapi.client.drive.files.list({'q': "title contains 'bookmarks'"}).execute(function(response){
				if(response.error){
					Ext.MessageBox.alert('ALERT',response.error.code+' '+response.error.message,function(){window.location='/quickstart.html';});
					return;
				}
				else{
					var file = response.items[0];
					if (file.downloadUrl) {
							var accessToken = gapi.auth.getToken().access_token;
							
							$.support.cors = true;
							$.ajax({
								url: file.downloadUrl,
								type: "GET",
								crossDomain: true,
								beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);},
								success: function(data) {
									var i;
									var massToBeSorted = Ext.decode(data);
									massToBeSorted.sort(function(a,b){return a.id-b.id;});
									store.removeAll();
									for(i=0;i<massToBeSorted.length;i++){
										store.insert(i,massToBeSorted[i]);
										store.getAt(i).setDirty();
									}
									store.filter({filterFn : function(rec) {return parseInt(rec.get("folderId"),10) === parseInt(window.controller.getCurrentFolderId(),10);}});
									
									store.sync();
									Ext.Msg.hide();
									
								},
								error:function(jqXHR,textStatus,errorThrown ){
									console.log(error);
								}
							});
							
					} else {
						store.loadRawData(null);
					}
				}
			});
		});
	},
	
	saveData:function(store,reloadDataFlag){
		var me = this;	
		this.updateStack.push({});
		
		var callback;
		if(reloadDataFlag){
	    	callback = function(){
		    	me.updateStack.shift();
		    	if(!me.updateStack.length){
		    		setTimeout(me.loadDataToStore(store),100);
		    	}
	    		console.log('Update Complete');
	    	};
		}		

		gapi.client.load('drive', 'v2', function() {
			gapi.client.drive.files.list({'q': "title contains 'bookmarks'"}).execute(function(response){
				if(response.error){
					Ext.MessageBox.alert('ALERT',response.error.code+' '+response.error.message,function(){window.location='/quickstart.html';});
					return;
					window.location.reload();
				}else{
					var file = response.items[0];
					var fileId = file.id;
					
					var count = 0;
					var expData = [];
					store.snapshot.each(function() {
						expData[count++] = this.data;
					});
					var text = Ext.encode(expData); 
					
					var boundary = '-------314159265358979323846',
					delimiter = "\r\n--" + boundary + "\r\n",
					close_delim = "\r\n--" + boundary + "--",
					contentType = "text/html",
					metadata = {'mimeType': contentType,};
					
					var multipartRequestBody =
						delimiter +  'Content-Type: application/json\r\n\r\n' +
						JSON.stringify(metadata) +
						delimiter + 'Content-Type: ' + contentType + '\r\n' + '\r\n' +
						text +
						close_delim;
					
					if (!callback) { callback = function(file) { 
						console.log("Update Complete ",file);
						Ext.Msg.hide();
					};}
					gapi.client.request({
						'path': '/upload/drive/v2/files/fileId='+fileId+"&uploadType=multipart",
						'method': 'PUT',
						'params': {'fileId': fileId, 'uploadType': 'multipart'},
						'headers': {'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'},
						'body': multipartRequestBody,
						callback:callback,
					});
				}
			});
		}); 		
	},	
	
	createNewFile:function(store){
		var me = this;
		
        var boundary = '-------314159265358979323846',
            delimiter = "\r\n--" + boundary + "\r\n",
            close_delim = "\r\n--" + boundary + "--";
	
          var contentType = 'text/html';
          var metadata = {
            'title': 'bookmarks',
            'mimeType': contentType
          };

          var multipartRequestBody =
              delimiter +
              'Content-Type: application/json\r\n\r\n' +
              JSON.stringify(metadata) +
              delimiter +
              'Content-Type: ' + contentType + '\r\n' +
              'Content-Transfer-Encoding: base64\r\n' +
              close_delim;

          var request = gapi.client.request({
              'path': '/upload/drive/v2/files',
              'method': 'POST',
              'params': {'uploadType': 'multipart'},
              'headers': {
                'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
              },
              'body': multipartRequestBody});
          var callback;
          if (!callback) {
            callback = function(file) {
              console.log(file);
            };
          }
          request.execute(callback);
        }
});